<?php
namespace App\Admin\Controller;

use App\Models\Giveout;
use App\Models\Goldcoins;
use App\Models\MemberUser;
use App\Models\OrderDollarCoin;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;
use ModStart\Admin\Concern\HasAdminCRUD;
use ModStart\Core\Util\QrcodeUtil;
use ModStart\Detail\Detail;
use ModStart\Field\AbstractField;
use ModStart\Form\Form;
use ModStart\Grid\Displayer\ItemOperate;
use ModStart\Grid\Grid;
use ModStart\ModStart;
use ModStart\Widget\TextDialogRequest;

class GoldcoinsController extends Controller
{
    use HasAdminCRUD;
    public function grid()
    {
        $grid = Grid::make('goldcoins');
//        $grid->gridOperateAppend('<a href="javascript:;" data-dialog-request="/path/to/url" class="btn btn-primary">设置</a>');
        $grid->disableCUD();
        $grid->canDelete(false);
        $grid->id('id', 'ID');
        $grid->text('serial_number', '编号');
        $grid->text('coin_price', '金额');
        $grid->image('icon', '图标');
        $grid->select('out_id', '所属发行期')->optionArray($this->getBlogList(),'id','name');
        $grid->select('sale_state', '是否售卖')->options(['0' => '未售卖', '1' => '已售卖']);
        $grid->text('sale_user', '购买用户')->hookRendering(function (AbstractField $field, $item, $index) {
           if($item->sale_state == 1){
               $buy_inf = (new  OrderDollarCoin())->where(['dollar_coin_id'=>$item->id,'is_pay'=>1])->first();
               if($buy_inf){
                  $user_info =  (new MemberUser())->where(['id'=>$buy_inf->user_id])->first();
                   return '<span>'.$user_info->nickname.'</span>';
               }
           }
            return '<span>无</span>';
        });
        $grid->display('created_at', '创建时间');
        $grid->hookItemOperateRendering(function (ItemOperate $itemOperate) {
            $item = $itemOperate->item();
//            $itemOperate->prepend("<a href='goldcoins/getqrcode/'".$item['id'].">下载二维码</a>");
            $itemOperate->push(TextDialogRequest::primary('二维码', modstart_admin_url('goldcoins/getqrcode/'.$item['id'])));
        });
        $this->pageTitle('货币管理');
        return $grid;
    }



    public function getBlogList(){
        $res =  DB::table("giveout")->select("id","title as text")->get();
        $lit = [];
        foreach($res as $k => $v){
            $lit[$k]['id'] = $v->id;
            $lit[$k]['name'] = $v->text;
        }
        return $lit;
    }



    public function form()
    {
        $form = Form::make('goldcoins');
        $form->text('serial_number', '编号');
        $form->text('coin_price', '金额');
        $form->image('icon', '图标');
        $form->select('out_id', '所属发行期')->optionArray($this->getBlogList(),'id','name')->readonly(true);
        $form->select('sale_state', '是否售卖')->options(['0' => '未售卖', '1' => '已售卖']);
//        $form->hookSaving(function (Form $form) {
//            if ($form->isModeAdd()) {
//                // 增加模式
//                $data = $form->dataAdding();
//                // 替换入库数据
//                $form->dataAdding($data);
//            } else if ($form->isModeEdit()) {
//                // 修改
//                $data = $form->dataEditing();
//                // 替换入库数据
//                $form->dataEditing($data);
//            }
//        });
        return $form;
    }
    public function detail()
    {
        $detail = Detail::make('goldcoins');
        $detail->id('id', 'ID');
        $detail->display('created_at', '创建时间');
        $detail->text('serial_number', '编号');
        $detail->text('coin_price', '金额');
        $detail->image('icon', '图标');
        $detail->select('out_id', '所属发行期')->optionArray($this->getBlogList(),'id','name')->readonly(true);
        $detail->select('sale_state', '是否售卖')->options(['0' => '未售卖', '1' => '已售卖']);
        return $detail;
    }

    public function getqrcode($id)
    {
        $result = (new Goldcoins())->where(['id'=>$id])->first();
        $phase = (new Giveout())->where(['id'=>$result->out_id])->first();
        if(!$result){
            return Response::generate(-1, '该货币不存在!');
        }
        //$url = config("app.host_uri")."/getGoldcoins/getDetail/".$result->id;
        $url = config("app.host_uri")."/#/qrcode?id=".$result->id;
        $path_uri = public_path("qrcode/images/".$phase->id.'/');
        if(!is_dir($path_uri)){
            mkdir($path_uri,'0755',true);
        }
        $file_uri = $path_uri.$result->serial_number.'.png';
        if(!file_exists($file_uri)){
            $qrCode =  QrcodeUtil::png($url,300);
            // 实例化图像处理器
            $image = Image::make($qrCode);
            // 保存图片到服务器
            $image->save($file_uri);
            $qr_uri = 'http://'.$_SERVER['HTTP_HOST']."/qrcode/images/".$phase->id.'/'.$result->serial_number.'.png';
        }else{
            $qr_uri = 'http://'.$_SERVER['HTTP_HOST']."/qrcode/images/".$phase->id.'/'.$result->serial_number.'.png';
        }
        $str = "<div style='width: 50%;height:50%;margin:0 auto;margin-top: 100px'>
                   <img src='$qr_uri'/>
                   <div style='margin:20px 60px;  margin-top: 50px;  width: 150px;
    height: 40px;background: #3555cc;text-align: center;line-height:40px;border-radius: 2% '><a href='$qr_uri?response-content-type=application/octet-stream' download  style='color:#f0f0f0;text-decoration: none;'>下载二维码</a></div>
                   </div>";
        return $str;
    }
}